/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import React, { useEffect, useRef, useState } from 'react';
import styles from './styles.module.css';

export default function ShowcaseTooltip({
  children,
  text,
}: {
  children: React.ReactNode;
  text: string;
}) {
  const [showTooltip, setShowTooltip] = useState(false);
  const tooltipId = useRef(`tooltip-${Math.random().toString(16).slice(2)}`);
  const timeout = useRef<number | null>(null);

  const showTooltipWithDelay = () => {
    timeout.current = window.setTimeout(() => {
      setShowTooltip(true);
    }, 500);
  };

  const hideTooltipWithDelay = () => {
    if (timeout.current) {
      window.clearTimeout(timeout.current);
      timeout.current = null;
    }
    setShowTooltip(false);
  };

  useEffect(() => {
    return () => {
      if (timeout.current) {
        window.clearTimeout(timeout.current);
      }
    };
  }, []);

  return (
    <div className={styles.tooltipContainer}>
      <div
        onMouseEnter={showTooltipWithDelay}
        onMouseLeave={hideTooltipWithDelay}
        aria-describedby={tooltipId.current}>
        {children}
      </div>
      {showTooltip && (
        <div
          id={tooltipId.current}
          className={styles.tooltip}
          role="tooltip">
          {text}
        </div>
      )}
    </div>
  );
}
